<?php

class Superlike_Api_Core extends Core_Api_Abstract
{
  /**
   * The action attachments
   * 
   * @var mixed
   */
  protected $_attachments;
	
  protected $_custom = false;
  protected $_table = null;	
  protected $_poster = null;
  protected $_resource = null;
  
  public function __construct()
  {
    $this->_poster = Engine_Api::_()->user()->getViewer();
  }
  
  public function likes(Core_Model_Item_Abstract $resource)
  {
  	if(get_class($resource) == 'Activity_Model_Action'){
  		$this->_custom = true;
  		$this->_table = Engine_Api::_()->getDbtable('superlikes', 'activity');
	    $commentable = $this->getTypeInfo($resource)->commentable;

	    switch( $commentable ) {
	      // Comments linked to action item
	      default: case 0: case 1:
	        $this->_resource = $resource;
	        break;
	
	      // Comments linked to subject
	      case 2:
	        $this->_resource = $resource->getSubject();
	        $this->_table = Engine_Api::_()->getDbTable('superlikes','superlike');
	        $this->_custom = false;
	        break;
	
	      // Comments linked to object
	      case 3:
	        $this->_resource = $resource->getObject();
	        $this->_table = Engine_Api::_()->getDbTable('superlikes','superlike');
	        $this->_custom = false;
	        break;
	
	      // Comments linked to the first attachment
	      case 4:
	        $attachments = $this->getAttachments($resource);
	        if( !isset($attachments[0]) )
	        {
	          // We could just link them to the action item instead
	          throw new Activity_Model_Exception('No attachment to link comments to');
	        }
	        $this->_resource = $attachments[0];
	        $this->_table = Engine_Api::_()->getDbTable('superlikes','superlike');
	        $this->_custom = false;
	        break;
	    }
	
  	}else{
  		$this->_table = Engine_Api::_()->getDbTable('superlikes','superlike');
  		$this->_resource = $resource;
  	}

  	return $this;
  }
  
  public function getLikeTable()
  {
    return $this->_table;
  }
 
  public function addLike()
  {
  	$resource = $this->_resource;
  	$poster = $this->_poster; 
    $row = $this->getLike();
    if( null !== $row )
    {
      throw new Core_Model_Exception('Already liked');
    }

    $table = $this->getLikeTable();

    $row = $table->createRow();

    if( isset($row->resource_type) )
    {
      $row->resource_type = $resource->getType();
    }

    $row->resource_id = $resource->getIdentity();
    $row->poster_type = $poster->getType();
    $row->poster_id = $poster->getIdentity();
    $row->save();

//    if( isset($resource->like_count) )
//    {
//      $resource->like_count++;
//      $resource->save();
//    }

    return $row;
  }

  public function removeLike()
  {
  	
  	$resource = $this->_resource;
  	$poster = $this->_poster;
  	
    $row = $this->getLike();
    if( null === $row )
    {
      throw new Core_Model_Exception('No like to remove');
    }

    $row->delete();

//    if( isset($resource->like_count) )
//    {
//      $resource->like_count--;
//      $resource->save();
//    }

    return $this;
  }

  public function isLike()
  {
  	$resource = $this->_resource;
  	$poster = $this->_poster;
    return ( null !== $this->getLike() );
  }

  public function getLike()
  {
  	$resource = $this->_resource;
  	$poster = $this->_poster;
  	
    $table = $this->getLikeTable();
    $select = $this->getLikeSelect($resource)
      ->where('poster_type = ?', $poster->getType())
      ->where('poster_id = ?', $poster->getIdentity())
      ->limit(1);

    return $table->fetchRow($select);
  }

  public function getLikeSelect()
  {
  	$resource = $this->_resource;
    $select = $this->getLikeTable()->select();

    if( !$this->_custom )
    {
      $select->where('resource_type = ?', $resource->getType());
    }

    $select
      ->where('resource_id = ?', $resource->getIdentity())
      ->order('superlike_id ASC');

    return $select;
  }

  public function getLikePaginator()
  {
  	$resource = $this->_resource;
  	
    $paginator = Zend_Paginator::factory($this->getLikeSelect($resource));
    $paginator->setItemCountPerPage(3);
    $paginator->count();
    $pages = $paginator->getPageRange();
    $paginator->setCurrentPageNumber($pages);
    return $paginator;
  }

  public function getLikeCount()
  {
  	 $resource = $this->_resource;

//    if( isset($resource->like_count) )
//    {
//      return $resource->like_count;
//    }

    $select = new Zend_Db_Select($this->getLikeTable()->getAdapter());
    $select
      ->from($this->getLikeTable()->info('name'), new Zend_Db_Expr('COUNT(1) as count'));

    if( !$this->_custom )
    {
      $select->where('resource_type = ?', $resource->getType());
    }

    $select->where('resource_id = ?', $resource->getIdentity());

    $data = $select->query()->fetchAll();
    return (int) $data[0]['count'];
  }

  public function getAllLikes()
  {
  	$resource = $this->_resource;
  	
    return $this->getLikeTable()->fetchAll($this->getLikeSelect($resource));
  }

  public function getAllLikesUsers()
  {
  	$resource = $this->_resource;
  	
    $table = $this->getLikeTable();
    $select = new Zend_Db_Select($table->getAdapter());
    $select->from($table->info('name'), array('poster_type', 'poster_id'));

    if( !$this->_custom )
    {
      $select->where('resource_type = ?', $resource->getType());
    }

    $select->where('resource_id = ?', $resource->getIdentity());

    $users = array();
    foreach( $select->query()->fetchAll() as $data )
    {
      if( $data['poster_type'] == 'user' )
      {
        $users[] = $data['poster_id'];
      }
    }
    $users = array_values(array_unique($users));

    return Engine_Api::_()->getItemMulti('user', $users);
  }
  
  public function getAttachments($action)
  {
    if( null !== $this->_attachments )
    {
      return $this->_attachments;
    }

    if( $action->attachment_count <= 0 )
    {
      return null;
    }

    $table = Engine_Api::_()->getDbtable('attachments', 'activity');
    $select = $table->select()
      ->where('action_id = ?', $action->action_id);

    foreach( $table->fetchAll($select) as $row )
    {
      $item = Engine_Api::_()->getItem($row->type, $row->id);
      if( $item instanceof Core_Model_Item_Abstract )
      {
        $val = new stdClass();
        $val->meta = $row;
        $val->item = $item;
        $this->_attachments[] = $val;
      }
    }

    return $this->_attachments;
  }

  /**
   * Get the type info
   *
   * @return Engine_Db_Table_Row
   */
  public function getTypeInfo($action)
  {
    $info = Engine_Api::_()->getDbtable('actionTypes', 'activity')->getActionType($action->type);
    if( !$info )
    {
      //throw new Exception('Missing Action Type: ' . $this->type);
    }
    return $info;
  }
  
}